<template>
	<view class="page">
		<custom-header bgColor="bg-white">
			<view slot="header" class="header">
				<view class="title">用户登录</view>
			</view>
		</custom-header>
		<view class="body">
			<view class="banner">
				<image :src="web_host + '/images/wxapp_banner1.jpg'" mode="widthFix"></image>
			</view>
			<view class="login-tab">
				<!-- <view :class="['item',{'active':login_type==1}]" @click="changeLoginType(1)">验证码登录</view> -->
				<!-- <view :class="['item']" @click="changeLoginType(2)">账号登录</view> -->
			</view>
			<view class="login-wrap">
				<view :class="['login-form', { active: login_type == 2 }]">
					<view class="item">
						<view class="icon">
							<image src="@/static/images/user.png" mode="widthFix"></image>
						</view>
						<input type="text" v-model="user_name" value="" placeholder="请输入登录账号" />
					</view>
					<view class="item">
						<view class="icon">
							<image src="@/static/images/pw.png" mode="widthFix"></image>
						</view>
						<!-- <input :type="isProclaimedPw ? 'text' : 'password'" v-model="password" value="" placeholder="请输入登录密码" /> -->
						<input v-if="isProclaimedPw" type="text" v-model="password" value="" placeholder="请输入登录密码" />
						<input v-else type="password" v-model="password" value="" placeholder="请输入登录密码" />

						<view class="icon" v-if="pwLength > 0" @click="proclaimedPw">
							<image v-if="isProclaimedPw" src="@/static/images/password_show.png" mode="widthFix" style="width: 60%;"></image>
							<image v-else src="@/static/images/password_hide.png" mode="widthFix" style="width: 60%;"></image>
						</view>
					</view>
					<view class="link-bar">
						<view class="re-pw" @click="remberPw">
							<view class="icon">
								<view v-if="isRemberPw" class="iconfont f-s36 active">&#xe640;</view>
								<view v-else class="iconfont f-s36">&#xe656;</view>
							</view>
							<view class="re-pw-text">记住密码</view>
						</view>
						<!-- <view class="find-pw">
							<view class="find-pw-text">忘记密码</view>
						</view> -->
					</view>
					<view class="btn" @click="login">登录</view>

					<!-- #ifdef APP-PLUS -->
					<view class="agreerule">
						<view class="icon" @click="setAgree">
							<radio color="#0085ff" :checked="isAgree"></radio>
							<text>阅读并同意</text>
						</view>
						<view class="agreerule-text">
							<!-- {{ app_name }} -->
							<navigator open-type="navigate" url="/package_member/authorization/authorization?type=2" hover-class="none">《隐私政策》</navigator>
							<navigator open-type="navigate" url="/package_member/authorization/authorization?type=3" hover-class="none">《用户服务协议》</navigator>
							<!-- 服务条款 -->
						</view>
					</view>

					<!-- #endif -->
				</view>

				<view :class="['login-form', { active: login_type == 1 }]">
					<view class="item">
						<view class="icon">
							<image src="@/static/images/user.png" mode="widthFix"></image>
						</view>
						<input type="text" v-model="phone" value="" placeholder="请输入手机号码" />
					</view>
					<view class="item code-bar">
						<view class="icon">
							<image src="@/static/images/phone_code.png" mode="widthFix"></image>
						</view>
						<input type="password" v-model="phone_code" value="" placeholder="请输入验证码" />
						<view class="get-code-btn">获取验证码</view>
					</view>
					<view class="btn" @click="login">登录</view>
				</view>
			</view>
			<!-- <button open-type="getUserInfo" class="login-wechat" hover-class="none" @click="getUserInfo">
				<view class="icon">
					<image src="@/static/images/wechat.png" mode="widthFix"></image>
				</view>
				<view class="text">微信登录</view>
			</button> -->

			<!-- <view class="agreerule">
			<view class="icon" @click="agreerule">
				<view v-if="isAgreerule" class="iconfont f-s36 active">&#xe640;</view>
				<view v-else class="iconfont f-s36">&#xe656;</view>				
			</view>
			<view class="agreerule-text">阅读并同意《<navigator url="/">{{app_name}}服务条款</navigator>》</view>
			</view> -->
		</view>

		<view v-if="flag.isFullPage" class="full-fix-page">
			<view v-if="flag.isGetCode" class="popup-wrap a-fadein">
				<view class="popup-type-model ">
					<view class="close-btn iconfont f-s54" @click="closeSendCode">&#xe65b;</view>
					<view class="popup-body">
						<view class="title">验证手机</view>
						<view class="content get-code-popup">
							<view class="phone-text">手机号：{{ phone }}</view>
							<view class="code-bar">
								<input type="number" v-model="phone_code" />
								<view class="get-code-btn" @click="getCode">{{ count_time_text }}</view>
							</view>
							<view class="btn" @click="comfirmLogin">确定</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getCurrenPage, replaceStr } from '@/common/util.js';
	import Timer from '@/common/timer.js';
	import customHeader from '@/components/custom-header.vue';
	import { appid, appsecret, WEB_HOST } from '@/config.js';
	export default {
		name: 'name',
		data() {
			return {
				focusState: false,
				app_name: getApp().globalData.app_name,
				isStop: true,
				isWxStop: true,
				isRemberPw: true,
				isAgreerule: true,
				isSentCode: true,
				isComfirmLogin: true,

				// user_name: 'demo',
				// password: 'ruifengshengwu168',
				// phone_code: '909090',
				// isAgree: true,

				user_name: '',
				password: '',
				phone_code: '',
				isAgree: false,

				phone: '',
				appid: appid,
				appsecret: appsecret,
				userInfo: {},
				backtype: '',
				token: '',
				web_host: WEB_HOST,
				login_type: 2,
				flag: {
					// 弹窗相关
					isFullPage: false,
					isGetCode: false
				},
				count_time_text: '获取验证码',
				timer: null,
				isProclaimedPw: false, //是否密码明文
			};
		},
		onLoad(params) {
			console.log(params);
			this.backtype = params.backType;
			if (this.isRemberPw && uni.getStorageSync('loginInfo')) {
				this.user_name = uni.getStorageSync('loginInfo').user_name;
				this.password = uni.getStorageSync('loginInfo').password;
			}
		},
		onShow() {},
		methods: {
			// 是否记住密码
			remberPw: function() {
				this.isRemberPw = !this.isRemberPw;
			},

			//是否密码明文
			proclaimedPw() {
				this.isProclaimedPw = !this.isProclaimedPw;
				console.log(this.isProclaimedPw);
			},

			changeLoginType: function(type) {
				this.login_type = type;
			},

			login: async function() {
				console.log(this.isRemberPw);
				let _this = this;
				let code = '';
				if (this.isStop) {
					this.isStop = false;
					if (!this.user_name) {
						uni.showToast({
							icon: 'none',
							title: '请输入登录账号',
							mask: true,
							duration: 2000,
							success() {
								setTimeout(() => {
									_this.isStop = true;
								}, 300);
							}
						});
					} else if (!this.password) {
						uni.showToast({
							icon: 'none',
							title: '请输入登录密码',
							mask: true,
							duration: 2000,
							success() {
								setTimeout(() => {
									_this.isStop = true;
								}, 300);
							}
						});
					}
					// #ifdef APP-PLUS
					else if (!this.isAgree) {
						uni.showToast({
							icon: 'none',
							title: '请同意并阅读隐私政策与用户协议',
							mask: true,
							duration: 2000,
							success() {
								setTimeout(() => {
									_this.isStop = true;
								}, 300);
							}
						});
					}
					// #endif
					else {
						let token = await this.$api.user_api.getToken({
							appid: appid,
							appsecret: appsecret
						});
						if (token.data.ret == 1000) {
							this.token = token.data.data.token;
						}
						uni.showLoading({
							title: '登录中...'
						});

						// #ifdef MP-WEIXIN
						uni.login({
							provider: 'weixin',
							async success(res) {
								_this.getLoginUserInfo(_this, res);
							},
							fail(err) {
								uni.hideLoading();
								uni.showToast({
									icon: 'none',
									image: '../../static/images/error.png',
									title: '登录失败',
									mask: true,
									duration: 2000,
									success() {
										setTimeout(() => {
											_this.isStop = true;
										}, 300);
									}
								});
							}
						});
						// #endif

						// #ifdef APP-PLUS
						this.getLoginUserInfo(this);
						// #endif
					}
				}
			},

			async getLoginUserInfo(_this, res) {
				let params = {};
				let loginType = 0;
				// #ifdef MP-WEIXIN
				loginType = 0;
				params = {
					username: _this.user_name,
					password: _this.password,
					type: loginType,
					code: res.code,
					appid: appid,
					token: _this.token
				};
				// #endif
				// #ifdef APP-PLUS
				loginType = 3;
				params = {
					username: _this.user_name,
					password: _this.password,
					type: loginType,
					appid: appid,
					token: _this.token
				};
				// #endif
				let loginRes = await _this.$api.user_api.login(params);
				console.log('登录返回', loginRes.data);
				if (loginRes.data.ret == 0) {
					uni.setStorageSync('cookieKey', loginRes.header['Set-Cookie']);
					_this.userInfo = loginRes.data.data;
					if (loginRes.data.data.phone != 0) {
						uni.hideLoading();
						_this.phone = replaceStr(loginRes.data.data.phone, 3, '****');
						if (loginRes.data.data.is_phone == 1) {
							this.$store.commit('updateLoginState', true); // 登录状态更新   true 状态有更新
							// console.log('cookieKey',loginRes.header['Set-Cookie'])

							// 登录成功返回上一页
							uni.showToast({
								icon: 'success',
								title: '登录成功',
								mask: true,
								duration: 2000,
								success() {
									setTimeout(() => {
										if (_this.backtype && getCurrentPages() && getCurrentPages().length > 1) {
											// 登录成功更新上一页登录状态
											let prevPage = getCurrenPage(2);

											console.log('weixin-login');
											prevPage.$vm.loginStateUpdate = true;
											// if (prevPage.$vm.isSwitchTab) {
											// 	console.log("执行onload");
											// 	prevPage.onLoad();
											// }

											uni.navigateBack({
												delta: 1
											});
										} else {
											console.log('go-index');
											uni.switchTab({
												url: '/pages/index/index',
												success(e) {
													var pages = getCurrentPages().pop();
													pages.$vm.loginStateUpdate = true;
													if (pages == undefined || pages == null) return;
													// console.log(pages)
													// pages.onLoad();
												}
											});
										}
										setTimeout(() => {
											_this.isComfirmLogin = true;
										}, 300);
									}, 1000);
								}
							});
							// 保存用户信息
							uni.setStorage({
								key: 'userInfo',
								data: _this.userInfo
							});

							// 登录成功 是否记住登录账号密码
							if (_this.isRemberPw) {
								uni.setStorage({
									key: 'loginInfo',
									data: {
										user_name: _this.user_name,
										password: _this.password
									}
								});
							} else {
								uni.removeStorageSync('loginInfo');
							}

							uni.setStorage({
								key: 'token',
								data: _this.token
							});
						} else if (loginRes.data.data.is_phone == 0) {
							_this.showPopup('show', 'isGetCode');
						}
					} else {
						uni.hideLoading();
						uni.showModal({
							content: '检测到您未绑定手机号，请先绑定手机号',
							mask: true,
							cancelText: '暂不绑定',
							confirmText: '立即绑定',
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: `/pages/bind_account/bind_account?type=1&token=${_this.token}&userinfo=${JSON.stringify(_this.userInfo)}&pass=${_this.password}`
									});
								}
							}
						});
					}
					// 登录成功 是否记住登录账号密码
					if (_this.isRemberPw) {
						uni.setStorage({
							key: 'loginInfo',
							data: {
								user_name: _this.user_name,
								password: _this.password
							}
						});
					} else {
						uni.removeStorageSync('loginInfo');
					}

					setTimeout(() => {
						_this.isStop = true;
					}, 300);
				} else {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						image: '../../static/images/error.png',
						title: loginRes.data.message,
						mask: true,
						duration: 2000,
						success() {
							setTimeout(() => {
								_this.isStop = true;
							}, 300);
						}
					});
				}
			},

			getCode: async function() {
				let _this = this;
				if (this.isSentCode) {
					this.isSentCode = false;

					let res = await this.$api.user_api.sendSms({
						uid: this.userInfo.uid,
						appid: this.appid,
						token: this.token,
						phone: '',
						type: 1
					});
					if (res.data.ret == 1000) {
						this.timer = new Timer({
							type: '1',
							num: 60
						});
						this.timer.start({
							success: function(res) {
								_this.count_time_text = res + 's';
								_this.isSentCode = true;
							},
							complate: function() {
								_this.count_time_text = '获取验证码';
								_this.isSentCode = true;
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							image: '../../static/images/error.png',
							title: res.data.message,
							mask: true,
							duration: 2000,
							success() {
								setTimeout(() => {
									_this.isSentCode = true;
								}, 300);
							}
						});
					}
				}
			},

			comfirmLogin: async function() {
				let _this = this;
				if (this.phone_code == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入短信验证码',
						mask: true,
						duration: 2000
					});
				} else {
					if (this.isComfirmLogin) {
						this.isComfirmLogin = false;
						let res = await this.$api.user_api.checkSms({
							uid: this.userInfo.uid,
							appid: this.appid,
							token: this.token,
							code: this.phone_code,
							type: 2
						});
						if (res.data.ret == 1000) {
							this.showPopup('hide');
							this.$store.commit('updateLoginState', true); // 登录状态更新   true 状态有更新
							// console.log('cookieKey',loginRes.header['Set-Cookie'])

							// 登录成功返回上一页
							uni.showToast({
								icon: 'success',
								title: '登录成功',
								mask: true,
								duration: 2000,
								success() {
									setTimeout(() => {
										if (_this.backtype && getCurrentPages() && getCurrentPages().length > 1) {
											// 登录成功更新上一页登录状态
											let prevPage = getCurrenPage(2);

											console.log('weixin-login');
											prevPage.$vm.loginStateUpdate = true;
											// if (prevPage.$vm.isSwitchTab) {
											// 	console.log("执行onload");
											// 	prevPage.onLoad();
											// }

											uni.navigateBack({
												delta: 1
											});
										} else {
											console.log('go-index');
											uni.switchTab({
												url: '/pages/index/index',
												success(e) {
													var pages = getCurrentPages().pop();
													pages.$vm.loginStateUpdate = true;
													if (pages == undefined || pages == null) return;
													// console.log(pages)
													// pages.onLoad();
												}
											});
										}
										setTimeout(() => {
											_this.isComfirmLogin = true;
										}, 300);
									}, 1000);
								}
							});
							// 保存用户信息
							uni.setStorage({
								key: 'userInfo',
								data: _this.userInfo
							});

							// 登录成功 是否记住登录账号密码
							if (_this.isRemberPw) {
								uni.setStorage({
									key: 'loginInfo',
									data: {
										user_name: _this.user_name,
										password: _this.password
									}
								});
							} else {
								uni.removeStorageSync('loginInfo');
							}

							uni.setStorage({
								key: 'token',
								data: _this.token
							});
						} else {
							uni.showToast({
								icon: 'none',
								image: '../../static/images/error.png',
								title: res.data.message,
								mask: true,
								duration: 2000,
								success() {
									setTimeout(() => {
										uni.removeStorageSync('userInfo');
										uni.removeStorageSync('token');
										_this.isComfirmLogin = true;
									}, 300);
								}
							});
						}
					}
				}
			},

			closeSendCode: function() {
				this.phone_code = '';
				this.count_time_text = '获取验证码';
				uni.removeStorageSync('cookieKey');
				this.showPopup('hide');
				if (this.timer) {
					this.timer.stop();
				}
			},

			// 微信登录
			getUserInfo: function() {
				uni.getUserProfile({
					desc: '会员登录',
					success(res) {
						uni.login({
							provider: 'weixin',
							success(codeRes) {
								let code = codeRes.code;
							}
						});
					}
				});
			},
			getUserInfo1: function() {
				let _this = this;
				if (this.isWxStop) {
					this.isWxStop = false;
					uni.login({
						provider: 'weixin',
						async success(res) {
							let code = res.code;
							uni.getUserInfo({
								provider: 'weixin',
								async success(infoRes) {
									let loginRes = await _this.$api.user_api.login({
										code: code,
										type: 1
									});
									if (loginRes.data.ret == -2) {
										// 未绑定微信
										uni.showToast({
											icon: 'loading',
											title: '请先绑定账号',
											mask: true,
											duration: 2000,
											success() {
												uni.setStorageSync('cookieKey', loginRes.header['Set-Cookie']);
												setTimeout(() => {
													uni.navigateTo({
														url: '/pages/bind_account/bind_account'
													});
												}, 1000);
											}
										});
									} else {
										uni.setStorageSync('cookieKey', loginRes.header['Set-Cookie']);
									}
								}
							});
							setTimeout(() => {
								_this.isWxStop = true;
							}, 300);
						},
						fail() {
							setTimeout(() => {
								_this.isWxStop = true;
							}, 300);
						}
					});
				}
			},

			showPopup: function(t, n) {
				if (t == 'show') {
					this.flag.isFullPage = true;
					this.flag[n] = true;
				} else if (t == 'hide') {
					for (let i in this.flag) {
						this.flag[i] = false;
					}
				}
			},
			setAgree() {
				this.isAgree = !this.isAgree;
			}
		},
		onUnload() {
			if (this.timer) {
				this.timer.stop();
			}
		},
		components: {
			customHeader
		},
		computed: {
			pwLength() {
				return this.password.length;
			}
		},
		watch: {}
	};
</script>

<style lang="less">
	.page,
	page {
		background: #fff;
	}

	.banner {
		margin-bottom: 30rpx;
	}

	.login-tab {
		display: flex;
		width: 90%;
		margin: 0 auto 40rpx;

		.item {
			flex-grow: 1;
			line-height: 80rpx;
			text-align: center;
			font-size: 34rpx;
		}

		.active {
			border-bottom: 4rpx solid #09f;
			color: #09f;
		}
	}

	.login-wrap {
		.active {
			display: block;
		}
	}

	.login-form {
		@h: 90rpx;
		display: none;

		.item {
			display: flex;
			width: 90%;
			margin: 0 auto 40rpx;
			height: @h;
			line-height: @h;
			background: #f8f8f8;
			border-radius: 10rpx;

			.icon {
				width: @h;
				height: @h;
				text-align: center;
				line-height: @h;
				flex-shrink: 0;

				image {
					width: 50%;
					vertical-align: middle;
				}
			}

			input {
				flex-grow: 2;
				height: @h;
				line-height: @h;
				font-size: 30rpx;
			}
		}

		.btn {
			width: 90%;
			margin: 0 auto 50rpx;
			text-align: center;
			height: @h - 10;
			line-height: @h - 10;
			background: #0085ff;
			border-radius: 10rpx;
			color: #fff;
			font-size: 32rpx;
		}

		.agree-bar {
			display: flex;
			align-items: center;
			padding: 0 5%;
			color: #0085ff;
			font-size: 28rpx;

			radio {
				transform: scale(0.7);
				color: #ff9600;
			}

			.re-pw-text {
				display: flex;
			}

			navigator {
				color: #ff9600;
			}
		}
	}

	.code-bar {
		display: flex;
		height: 80rpx;
		border: 1rpx solid #eee;
		border-radius: 15rpx;
		margin-bottom: 40rpx;

		input {
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 10rpx;
			font-size: 30rpx;
		}

		.get-code-btn {
			flex-shrink: 0;
			width: 35%;
			line-height: 80rpx;
			text-align: center;
			font-size: 30rpx;
			color: #09f;
		}
	}

	.get-code-popup {
		.phone-text {
			margin-bottom: 30rpx;
			color: #666;
		}

		.btn {
			height: 70rpx;
			line-height: 70rpx;
			margin: 0 auto;
			background: #09f;
			border-radius: 8rpx;
			color: #fff;
			text-align: center;
			font-size: 30rpx;
		}
	}

	.re-pw {
		display: flex;
		height: 40rpx;
		line-height: 40rpx;

		// margin:40rpx 5% 80rpx;
		.icon {
			margin-right: 10rpx;
			color: #e5e5e5;
		}

		.active {
			color: #0085ff;
		}

		.re-pw-text {
			font-size: 30rpx;
			color: #222;
		}
	}

	.link-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 5% 80rpx;

		.find-pw-text {
			height: 40rpx;
			line-height: 40rpx;
			font-size: 30rpx;
			color: #0085ff;
		}
	}

	.agreerule {
		display: flex;
		text-align: center;
		justify-content: center;
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 40rpx;

		radio {
			transform: scale(0.7);
		}

		.icon {
			margin-right: 10rpx;
			color: #5f5f5f;
			font-size: 28rpx;
		}

		.active {
			color: #0085ff;
		}

		.agreerule-text {
			display: flex;
			font-size: 28rpx;
			color: #999;

			navigator {
				color: #0085ff;
			}
		}
	}

	.login-wechat {
		width: 50%;
		margin: 0 auto;

		.icon {
			width: 25%;
			margin: 0 auto;
		}

		.text {
			text-align: center;
			color: #ccc;
			font-size: 30rpx;
		}
	}
</style>